﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Interfaces;
using DataModel;
using FuzzyStrings;
using Helpers;

namespace SearchInDatabase
{
    [Export(typeof(IBookSearch))]
    [ExportMetadata("Rank",1)]
    [ExportMetadata("Name","Database")]
    public class BookSearch : IBookSearch
    {
        public BookSearch()
        {
            Logger.Write("BookSearch() Database");
        }

        public List<Book> Search(string ISBN, string Title)
        {
            DataLayer data = DataLayer.Data;

            if ( ISBN != "")
                return data.Books.Where( x => x.ISBN == ISBN ).ToList();

            var b = data.Books
                .Select(x => new { id = x.ID, title = x.Title })
                .AsEnumerable()
                .Select(x => new { id = x.id, title = x.title, f = x.title.DiceCoefficient(Title) });
            var t = b
                .Where(x => x.f >= 0.333)
                .OrderByDescending(x => x.f)
                .Take(10)
                .Select(x => data.Books.Where(y => y.ID == x.id).First())
                .ToList();
            return t;
        }
    }
}
